package com.bootdo.shop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.Arith;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.hjh.dao.ProductPointsDOMapper;
import com.bootdo.hjh.dao.UserAddressMapper;
import com.bootdo.hjh.domain.ErrorConstant;
import com.bootdo.hjh.domain.ProductPointsDO;
import com.bootdo.hjh.domain.UserAddress;
import com.bootdo.hjh.ex.ThrowUtils;
import com.bootdo.hjh.service.PointsService;
import com.bootdo.shop.dao.GoodsMapper;
import com.bootdo.shop.dao.OrderMapper;
import com.bootdo.shop.domain.Calculating;
import com.bootdo.shop.domain.CalculatingDetail;
import com.bootdo.shop.domain.Goods;
import com.bootdo.shop.domain.GoodsConstant;
import com.bootdo.shop.domain.GoodsFromCart;
import com.bootdo.shop.domain.GoodsLimit;
import com.bootdo.shop.domain.ImputedPrice;
import com.bootdo.shop.domain.ImputedPriceDetail;
import com.bootdo.shop.domain.OrderConstant;
import com.bootdo.shop.domain.OrderDetail;
import com.bootdo.shop.domain.OrderInfo;
import com.bootdo.shop.domain.PostageConfig;
import com.bootdo.shop.domain.request.OrderInfoReq;
import com.bootdo.shop.domain.request.ShoppingCartReq;
import com.bootdo.shop.domain.response.GoodsRes;
import com.bootdo.shop.domain.response.OrderDetailsRes;
import com.bootdo.shop.domain.response.OrderInfoRes;
import com.bootdo.shop.domain.response.ShoppingCartRes;
import com.bootdo.shop.service.GoodsService;
import com.bootdo.shop.service.ShopOrderService;
import com.bootdo.shop.service.ShoppingCartService;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;


@Service
public class ShopOrderServiceImpl implements ShopOrderService{

	private static final Logger logger = LoggerFactory.getLogger(ShopOrderServiceImpl.class);

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserAddressMapper userAddressMapper;

	@Autowired
	private ShoppingCartService shoppingCartService;

	@Autowired
	private ProductPointsDOMapper productPointsDOMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private UserDao userDao;

	@Autowired
	private PointsService pointsService;

	@Override
	@Transactional
	public OrderInfoRes createOrder(OrderInfoReq orderInfoReq) {
		logger.info("orderInfoReq : {}",JSONObject.toJSONString(orderInfoReq));
		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() == 0){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
		}
//		if(orderInfoReq.getSource() == null){
//			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单来源不能为空");
//		}
		//商品总购买数量
		Integer goodsNumber = 0;
		//用户收货地址,如果有实体商品时会赋值
		UserAddress userAddress = null;
		String orderTitle = null;
		String orderImg = null;
		//是否有实体商品
		Boolean shippingFlag = false;
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		//订单实体
		OrderInfoRes orderInfo = new OrderInfoRes();
		for(OrderDetail od : orderInfoReq.getOrderDetails()){
			if(od.getSpecificationId() == null){
				od.setSpecificationId(0);
			}
			OrderDetail orderDetail = new OrderDetail();
			boolean addressFlag = false;
			if(od.getType() == null){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "参数错误,商品类型不能为空");
			}
			//订单类型
			orderDetail.setType(od.getType());
			if(od.getGoodsNumber() == null || od.getGoodsNumber() == 0){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			goodsNumber += od.getGoodsNumber();
			//如果是实体商品 或非服务订单
			if(od.getType().intValue() != GoodsConstant.GOODS_TYPE_SERVICE.getStatus()){
				Goods goods = goodsMapper.getGoodsById(od.getGoodsId());
				if(goods == null){
					ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品不存在");
				}
				//校验限购
				verifyLimitations(orderInfoReq.getUserId(), od.getGoodsId(), od.getSpecificationId(), od.getGoodsNumber());
				if(orderImg == null){
					orderImg = goods.getThumbnailImage();
				}
				orderTitle = goods.getTitle();

				if(goods.getIsOnsale() == 2){
					ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品已下架");
				}
				//检查库存
				goodsService.subtractStock(od.getGoodsId(), od.getGoodsNumber(),od.getSpecificationId());

				orderDetail.setSpecificationId(od.getSpecificationId());
				orderDetail.setGoodsName(goods.getTitle());//商品名称
				orderDetail.setSalePrice(goods.getSalePrice());//交易价格
				Integer realPrice = (goods.getSalePrice() * od.getGoodsNumber());
				orderDetail.setRealPrice(realPrice);//该商品实际总价
				orderDetail.setMarketPrice(goods.getMarketPrice());//市场价
				orderDetail.setThumbnailImage(goods.getThumbnailImage());
				orderDetail.setGoodsId(goods.getId());//商品ID
				orderDetail.setGoodsNumber(od.getGoodsNumber());//购买数量

				//查询收货地址 并且配送
				if(!addressFlag && goods.getIsExpress().intValue() == GoodsConstant.GOODS_EXPRESS.getStatus().intValue()){
					//判断收货地址ID是否为空
					if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() ==0){
						ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户收货地址不能为空");
					}
					userAddress = userAddressMapper.getUserAddressById(orderInfoReq.getUserAddressId());
					if(userAddress == null ){
						ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到用户收货地址");
					}else{
						addressFlag = true;
					}
				}
				orderDetail.setIsService(0);//非服务
				orderDetail.setIsReal(1);//实体商品
				//是否赠品
				if(null != goods.getIsGift() && goods.getIsGift() == 1){
					orderDetail.setIsGift(1);
				}else{
					orderDetail.setIsGift(0);
				}
				shippingFlag = true;
				orderInfo.setGoodsType(goods.getGoodsType());
			}
			orderDetails.add(orderDetail);
		}

		String orderNo = StringUtils.generateOrderNO("A");
		orderInfo.setOrderNo(orderNo);//订单编号
		orderInfo.setUserId(orderInfoReq.getUserId());
		orderInfo.setOrderStatus(OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus());//订单状态 默认为已确认
		//如果是实体商品
		if(null != userAddress){
			orderInfo.setReceiver(userAddress.getName());
			orderInfo.setProvince(userAddress.getProvince());
			orderInfo.setCity(userAddress.getCity());
			orderInfo.setDistrict(userAddress.getDistrict());
			orderInfo.setAddress(userAddress.getAddress());
			orderInfo.setPostcode(userAddress.getPostcode());
			orderInfo.setTel(userAddress.getTel());
			orderInfo.setMobile(userAddress.getMobile());
		}
		orderInfo.setServiceMobile(orderInfoReq.getServiceMobile());
		//购买物品数量
		orderInfo.setGoodsNumber(goodsNumber);
		//订单金额 （购物数量 * 商品交易金额）
		//计算价格
		//ImputedPrice imputedPrice = calculatePostage(orderInfoReq);
		UserDO userDO = userService.get(orderInfoReq.getUserId());
		ShoppingCartReq shoppingCartReq = new ShoppingCartReq();
		shoppingCartReq.setUserId(orderInfoReq.getUserId());
		shoppingCartReq.setMemberLevel(userDO.getMemberLevel());
		shoppingCartReq.setAgentLevel(userDO.getAgentLevel());
		List<ShoppingCartRes> list = shoppingCartService.getShoppingCartList(shoppingCartReq);

		Calculating calculating = calculatingPrice(list, userDO);

		//订单总金额 订单金额 + 运费 - 优惠券金额
		orderInfo.setOrderTitle(orderTitle);
		orderInfo.setOrderImg(orderImg);
		orderInfo.setCouponId(orderInfoReq.getCouponId());
		orderInfo.setCouponAmount(calculating.getShopCreditTotal());//优惠金额
		orderInfo.setOrderPayee(calculating.getGoodsPriceTotal());//商品总金额
		orderInfo.setShippingPayee(0);//邮费
		orderInfo.setTotalPayee(calculating.getRealPayTotal());//总金额
		orderInfo.setFrAmount(calculating.getFrAmount());
		orderInfo.setIsInvoice(0);//不开发票
		orderInfo.setInvoiceAmount(0);//发票金额0
		orderInfo.setPayStatus(OrderConstant.PAY_STATUS_NON_PAYMENT.getOrderStatus());//支付状态
		//买家留言
		orderInfo.setBuyerMemo(orderInfoReq.getBuyerMemo());//用户留言
		//订单来源
		orderInfo.setSource(orderInfoReq.getSource());//订单来源
		orderInfo.setExpirationTime(DateTime.now().plusDays(1).toDate());//过期时间
		orderInfo.setThirdpartyOrderNo(orderInfoReq.getThirdpartyOrderNo());//第三方订单号
		//保存订单
		orderInfo.setPayType(2);//支付方式 1:在线支付 2:货到付款
		//如果是货到付款,则订单需要人工确认
		if(orderInfoReq.getPayType() == OrderConstant.PAY_TYPE_COD.getOrderStatus()){
			orderInfo.setOrderStatus(OrderConstant.ORDER_STATUS_UNCONFIRMED.getOrderStatus());
		}
		//如果是线下支付订单，订单创建时间为可选参数 TODO
		orderInfo.setDiscountAmount(0);
		orderInfo.setStageAmount(0);
		orderInfo.setSubsidyAmount(0);
		orderInfo.setFinancialProgrammeDetailId(orderInfoReq.getFinancialProgrammeDetailId());
		orderMapper.createOrderInfo(orderInfo);
		//保存订单详情
		if(orderDetails.isEmpty()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "保存订单,订单详情不能为空");
		}
		//设置优惠金额、折扣金额、金融服务费
		for(OrderDetail detail :  orderDetails){
			if(detail.getSpecificationId() == null){
				detail.setSpecificationId(0);
			}
			for(CalculatingDetail cd :  calculating.getCalculatingDetail()){
				if(detail.getGoodsId().intValue() == cd.getGoodsId() ){
					detail.setDiscountRate(1d);
					detail.setDiscountAmount(0);
					detail.setStageMonths(0);
					detail.setStageInterestRate(1d);
					detail.setStageAmount(0);
					detail.setSubsidyRate(1d);
					detail.setSubsidyAmount(0);
					detail.setCouponAmount(cd.getShopCreditTotal());
					detail.setRealPrice(cd.getRealPayTotal());
				}
			}
		}
		orderMapper.batchCreateOrderDetail(orderDetails,orderInfo.getId());
		//清空购物车
		for(ShoppingCartRes scr : list) {
			ShoppingCartReq cart = new ShoppingCartReq();
			cart.setUserId(orderInfoReq.getUserId());
			cart.setGoodsId(scr.getGoodsId());
			shoppingCartService.deleteShoppingCart(cart);
		}
		return orderInfo;
	}

	@Override
	public void cancelOrder(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getId() == null || orderInfoReq.getId() == 0){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfo orderInfo = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == orderInfo){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单不存在");
		}
		if(orderInfoReq.getUserId().intValue() != orderInfo.getUserId().intValue()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该订单不属于您,不能取消");
		}
		//已支付不能取消
		if(orderInfo.getOrderStatus() == OrderConstant.PAY_STATUS_PREPAID.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已支付，不可取消.");
		}
		//已发货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_SHIPPED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已发货不可取消.");
		}
		//已收货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_RECEIVED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已收货不可取消.");
		}
		//已完成订单不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已完成不可取消.");
		}
		//已过期不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_EXPIRED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已过期不可取消.");
		}
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoReq.getId());
		for(OrderDetailsRes or : orderDetails){
			//如果不是服务,则商品库存加回去
			goodsService.increaseStock(or.getGoodsId(), or.getGoodsNumber(),or.getSpecificationId());
		}
		orderMapper.cancelOrderInfo(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_CANCELED.getOrderStatus());
		//添加订单操作日志
		addOrderActionLog(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_CANCELED.getOrderStatus(),
				null, null,"用户取消订单",null);
	}

	@Override
	public void confirmReceipt(OrderInfoReq orderInfoReq) {
		OrderInfoRes oir = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == oir){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到该订单.");
		}
		if(OrderConstant.SHIPPING_STATUS_UNFILLED.getOrderStatus().intValue() == oir.getShippingStatus().intValue()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品未发货.");
		}
		orderMapper.confirmReceipt(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus(),
				OrderConstant.SHIPPING_STATUS_RECEIVED.getOrderStatus());

		addOrderActionLog(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus(),
				null, null,"用户确认收货",null);
	}


	@Override
	public void consignment(OrderInfoReq orderInfoReq) {
		OrderInfoRes oir = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == oir){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到该订单.");
		}
		Integer orderStatus = 0;
		if(orderInfoReq.getShippingStatus() == 0) {
			orderStatus = OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus();
		}else if(orderInfoReq.getShippingStatus() == 1) {
			orderStatus = OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus();
		}else if(orderInfoReq.getShippingStatus() == 2) {
			orderStatus = OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus();
		}
		orderMapper.consignment(oir.getId(), orderStatus, orderInfoReq.getShippingStatus(),
				orderInfoReq.getShippingChannel(),
				orderInfoReq.getShiippingSn());
	}

	@Override
	public void paySuccessCallback(String orderNo, String payChannel, String buyerAccount, String chId) {
		OrderInfoRes oir = orderMapper.getOrderByOrderNo(orderNo);
		if(null == oir){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未找到订单号为："+orderNo+"的订单");
		}
		boolean isReal = false;
		List<OrderDetailsRes> orderDetailsRes = orderMapper.getOrderDetailList(oir.getId());
		for(OrderDetailsRes odr : orderDetailsRes){
			if(odr.getIsReal().intValue() == 1){
				isReal = true;
			}
		}
		if(isReal){
			orderMapper.updateOrderPaySuccessForReal(orderNo,
					payChannel, OrderConstant.PAY_STATUS_PREPAID.getOrderStatus(),chId);
		}else{
			orderMapper.updateOrderPaySuccessForService(orderNo,
					payChannel, OrderConstant.PAY_STATUS_PREPAID.getOrderStatus(),
					OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus(),chId);
		}
		//更新商品购买数量
		goodsService.updateGoodsBuyNumber(orderNo);
		addOrderActionLog(oir.getId(), OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus(),
				null, OrderConstant.PAY_STATUS_PREPAID.getOrderStatus(),"订单支付成功",null);

		//分润
		UserDO me = userDao.get(oir.getUserId());
		Long firstRecommendUserId = me.getRecommendUserId();
		Long secondRecommendUserId = null;
		if(firstRecommendUserId!=null){
			UserDO firstRecommendUser =  userDao.get(firstRecommendUserId);
			if(firstRecommendUser!=null){
				secondRecommendUserId = firstRecommendUser.getRecommendUserId();
			}
		}
//		pointsService.shopOrdersplit(oir.getUserId(), firstRecommendUserId, secondRecommendUserId, oir.getFrAmount());
		//扣减商品积分
		ProductPointsDO productPointsDO = new ProductPointsDO();
		productPointsDO.setAmount(-oir.getCouponAmount());
		productPointsDO.setCreateTime(new Date());
		productPointsDO.setLastModifyTime(new Date());
		productPointsDO.setType(100); //TODO 类型
		productPointsDO.setRemark("商城订单抵扣");
		productPointsDO.setUserId(oir.getUserId());
		productPointsDOMapper.insertSelective(productPointsDO);
	}

	@Override
	public ImputedPrice calculatePostage(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买商品不能为空");
		}
		ImputedPrice imputedPrice = new ImputedPrice();
		boolean isRela = false;
		boolean isPostFree = false;
		List<Integer> payTypeList = new ArrayList<Integer>();
		List<GoodsFromCart> gfcList = new ArrayList<>();
		for(OrderDetail od :  orderInfoReq.getOrderDetails()){

			if(od.getGoodsNumber() == null || od.getGoodsNumber() <= 0){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			if(od.getGoodsId() == null){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
			}
			if(od.getType() == null){
				od.setType(1);
				//ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品类型不能为空");
			}
			GoodsRes goodsRes = null;
			ImputedPriceDetail detail = new ImputedPriceDetail();
			detail.setGoodsId(od.getGoodsId());//商品ID
			detail.setGoodsNumber(od.getGoodsNumber());//购买数量
			GoodsFromCart gfc = new GoodsFromCart();
			gfc.setGoodsId(od.getGoodsId());
			gfc.setGoodsNum(od.getGoodsNumber());
			gfc.setType(od.getType());
			//gfc.setSpecificationId(od.getSpecificationId());
			gfcList.add(gfc);
			/**单个商品总交易份 = 单个商品交易份 * 购买数量**/
			//商城商品
			goodsRes = goodsMapper.getGoodsDetailById(od.getGoodsId());
			if(goodsRes == null){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品不存在");
			}
			//如果是赠品,则不计入价格
			if(null != goodsRes.getIsGift() && goodsRes.getIsGift() == 1){
				continue;
			}
			detail.setSalePrice(goodsRes.getSalePrice());
			detail.setTransactionPrice(detail.getSalePrice() * detail.getGoodsNumber());
			imputedPrice.setOrderAmount(imputedPrice.getOrderAmount() + detail.getTransactionPrice());
			//设置是是否要吧使用优惠券 和 可以使用优惠券的金额
			if(goodsRes.getIsUseCoupon() != null && goodsRes.getIsUseCoupon() == 1){
//					detail.setIsUseCoupon(true);
				imputedPrice.setUseCouponPrice(imputedPrice.getUseCouponPrice() + detail.getTransactionPrice());
			}
			//如果需要配送,下面会判断是否有收货地址
			if(goodsRes.getIsExpress() == 1){
				isRela = true;
			}
			//校验该商品包邮
			if(null != goodsRes.getPostFree() && goodsRes.getPostFree() == 1){
				isPostFree = true;
			}
			detail.setType(od.getType());
			imputedPrice.getDetails().add(detail);
		}
		if(isRela){
			//如果是实体商品,用户传了优惠券, 且 购买的商品都不可以使用优惠券,风抛出异常
			if(orderInfoReq.getCouponId() != null && orderInfoReq.getCouponId() > 0 && imputedPrice.getUseCouponPrice() <= 0){
				ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"该订单不支持优惠券");
			}
			PostageConfig postageConfig = null;
			if(orderInfoReq.getUserAddressId() != null && orderInfoReq.getUserAddressId() != 0){
//				if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() == 0){
//					ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "请输入收货地址");
//				}
				UserAddress userAddress = userAddressMapper.getUserAddressById(orderInfoReq.getUserAddressId());
				if(null == userAddress){
					ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户地址不存在");
				}
				postageConfig = goodsMapper.getPostageConfigByProvinceId(userAddress.getProvinceId());
			}
			//如果是线下订单,自定义了费用,以线下订单邮费为准
			if(null != orderInfoReq.getPayType()
					&& orderInfoReq.getPayType() == OrderConstant.PAY_TYPE_OFFLINE.getOrderStatus()
					&& orderInfoReq.getPostageAmount() != null && orderInfoReq.getPostageAmount() >= 0 ){
				imputedPrice.setPostageAmount(orderInfoReq.getPostageAmount());
			}else if(isPostFree){
				//包邮
				imputedPrice.setPostageAmount(0);
			}else if(postageConfig == null){
				//不在邮递范围内
				imputedPrice.setPostageAmount(0);
			}else{
				//商品价格在包邮范围内
				if(imputedPrice.getOrderAmount() >= postageConfig.getPinkagePrice() ){
					imputedPrice.setPostageAmount(0);
				}else{
					imputedPrice.setPostageAmount(postageConfig.getPostage());
				}
			}
		}
		imputedPrice.setUseCouponPrice(imputedPrice.getCouponAmount());
		for (ImputedPriceDetail detail : imputedPrice.getDetails()) {
			// 计算公司手续费 和 用户手续费
			if (orderInfoReq.getFinancialProgrammeDetailId() != null && orderInfoReq.getFinancialProgrammeDetailId() > 0) {
				Integer real = detail.getTransactionPrice() - detail.getDiscountAmount() - detail.getCouponAmount();
				Double sumStage = Arith.mul(real, detail.getStageMonths());
				Double stageAmount = Arith.mul(sumStage, detail.getStageInterestRate().doubleValue());
				//单个商品分期金额 = ((单个商品交易份 * 购买数量 ) - 单个商品优惠金额 ) * 分期利率 * 分期数
				detail.setStageAmount(Arith.doubleToIntRound(stageAmount));
				Double subsidyAmount = Arith.mul(detail.getSubsidyRate().doubleValue(), real);
				//公司手续费
				detail.setSubsidyAmount(Arith.doubleToIntRound(subsidyAmount));
			}
			//单个商品实付金额 = 单个商品交易份 * 购买数量 - 折扣金额 - 优惠券金额 + 金融服务费
//			detail.setRealPrice(detail.getTransactionPrice() -detail.getDiscountAmount() - detail.getCouponAmount() + detail.getStageAmount());
			detail.setRealPrice(detail.getTransactionPrice());
			imputedPrice.setStageAmount(imputedPrice.getStageAmount() + detail.getStageAmount());
			imputedPrice.setSubsidyAmount(imputedPrice.getSubsidyAmount() + detail.getSubsidyAmount());
		}
		//订单总价 = 商品总价 - 折扣金额 -  + 运费 - 优惠券 + 金融服务费
		Integer totalAmount = imputedPrice.getOrderAmount().intValue() +
				- imputedPrice.getDiscountAmount().intValue()
				+ imputedPrice.getPostageAmount().intValue()
				- imputedPrice.getCouponAmount().intValue()
				+ imputedPrice.getStageAmount().intValue();
		if(totalAmount < 0){
			totalAmount = 0;
		}

		imputedPrice.setTotalAmount(totalAmount);
		//支付方式
		if(imputedPrice.getTotalAmount() == 0){
			//如果订单金额为0时，只支付在线支付
			imputedPrice.setPayType(OrderConstant.PAY_TYPE_ONLINE.getOrderStatus());
		}else if(null == payTypeList || payTypeList.isEmpty()){
			//如果为空只能在线支付
			imputedPrice.setPayType(OrderConstant.PAY_TYPE_ONLINE.getOrderStatus());
		}else if(payTypeList.contains(OrderConstant.PAY_TYPE_ONLINE.getOrderStatus())){
			//如果有在线支付商品,该订单只能在线支付
			imputedPrice.setPayType(OrderConstant.PAY_TYPE_ONLINE.getOrderStatus());
		}else if(payTypeList.contains(OrderConstant.PAY_TYPE_ONLINE_AND_COD.getOrderStatus())){
			//如果有在线支付和货到付款,只能是在线支付
			imputedPrice.setPayType(OrderConstant.PAY_TYPE_ONLINE_AND_COD.getOrderStatus());
		}else if(payTypeList.contains(OrderConstant.PAY_TYPE_COD.getOrderStatus())){
			//如果以上两种情况都没有,只能是货到付款
			imputedPrice.setPayType(OrderConstant.PAY_TYPE_COD.getOrderStatus());
		}
		return imputedPrice;
	}

	public Calculating calculatingPrice(List<ShoppingCartRes> list,UserDO userDO) {
		Calculating calculating = new Calculating();
		Integer goodsPriceTotal = 0;
		Integer shopCreditTotal = 0;
		Integer frAmount = 0;
		List<CalculatingDetail>  calculatingDetailList = new ArrayList<>();
		for(ShoppingCartRes shoppingCartRes : list) {
			CalculatingDetail calculatingDetail = new CalculatingDetail();
			if(shoppingCartRes.getIsDisable()) {
				continue;
			}
			Integer credit = 0;
			if(userDO.getAgentLevel() != null && userDO.getAgentLevel() > 0 ) {
				switch (userDO.getAgentLevel()) {
				case 1:
					credit = shoppingCartRes.getAgent1Credits();
					break;
				case 2:
					credit = shoppingCartRes.getAgent2Credits();
					break;
				case 3:
					credit = shoppingCartRes.getAgent3Credits();
					break;
				case 4:
					credit = shoppingCartRes.getAgent4Credits();
					break;
				case 5:
					credit = shoppingCartRes.getAgent5Credits();
					break;
				default:
					break;
				}
			}else {
				switch (userDO.getMemberLevel()) {
				case 1:
					credit = shoppingCartRes.getGeneralUserCredits();
					break;
				case 2:
					credit = shoppingCartRes.getPlatinaUserCredits();
					break;
				case 3:
					credit = shoppingCartRes.getVipUserCredits();
					break;
				default:
					break;
				}
			}
			credit = credit == null ? 0 : credit;
			if(credit > shoppingCartRes.getSalePrice()) {
				credit = shoppingCartRes.getSalePrice();
			}
			calculatingDetail.setGoodsPriceTotal(shoppingCartRes.getSalePrice());
			shoppingCartRes.setShopCredit(credit);
			calculatingDetail.setShopCreditTotal(shoppingCartRes.getShopCredit());
			shoppingCartRes.setRealPay(shoppingCartRes.getSalePrice() - shoppingCartRes.getShopCredit());
			if(shoppingCartRes.getRealPay() < 0) {
				shoppingCartRes.setRealPay(0);
			}
			calculatingDetail.setGoodsNum(shoppingCartRes.getGoodsNum());
			calculatingDetail.setGoodsId(shoppingCartRes.getGoodsId());
			Integer totalPrice = shoppingCartRes.getRealPay() * shoppingCartRes.getGoodsNum();
			shoppingCartRes.setTotalPrice(totalPrice);
			if(shoppingCartRes.getIsFr() != null && shoppingCartRes.getIsFr() == 1) {
				frAmount += shoppingCartRes.getTotalPrice();
			}
			calculatingDetail.setRealPayTotal(shoppingCartRes.getTotalPrice());
			goodsPriceTotal += shoppingCartRes.getSalePrice() * shoppingCartRes.getGoodsNum();
			shopCreditTotal += credit * shoppingCartRes.getGoodsNum();
			calculatingDetailList.add(calculatingDetail);
		}
		calculating.setCalculatingDetail(calculatingDetailList);
		calculating.setGoodsPriceTotal(goodsPriceTotal);
		calculating.setShopCreditTotal(shopCreditTotal);
		calculating.setFrAmount(frAmount);
		Integer realPayTotal = goodsPriceTotal - shopCreditTotal;
		calculating.setRealPayTotal(realPayTotal <= 0 ? 0 : realPayTotal);
		return calculating;
	}

	@Override
	public void updateOrderAddress(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getId() == null || orderInfoReq.getId() == 0){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfo orderInfo = orderMapper.getOrderInfoByOrderId(orderInfoReq.getId());
		if(orderInfo == null){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单不存在");
		}
		//检查是仓库是否已发货
		Integer isDelivery = orderMapper.checkStoreDeliveryList(orderInfo.getId());
		if(isDelivery > 0){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该订单已发货, 不可修改收货地址");
		}
		orderMapper.updateOrderAddress(orderInfoReq);
		addOrderActionLog(orderInfoReq.getId(), null,
				null, null,"修改收货地址",orderInfoReq.getActionUser());

	}

	@Override
	public void addOrderActionLog(Integer orderId, Integer orderStatus, Integer shippingStatus, Integer payStatus,
			String actionNote, String actionUser) {
		orderMapper.insertOrderActionLog(orderId, orderStatus, shippingStatus, payStatus,actionNote,actionUser);

	}

	@Override
	public OrderInfoRes updateOrderPayStatusForPaymentIn(Integer orderId) {
		OrderInfoRes oir = orderMapper.getOrderById(orderId);
		if(oir == null){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单不存在");
		}
		//只有订单状态为未支付时，才可变更状态为支付中
		if(null != oir.getPayStatus() &&
				oir.getPayStatus().intValue() == OrderConstant.PAY_STATUS_NON_PAYMENT.getOrderStatus()){
			orderMapper.updateOrderPayStatusForPaymentIn(orderId , OrderConstant.PAY_STATUS_PAYMENT_IN.getOrderStatus() );
			oir = orderMapper.getOrderById(orderId);
		}
		return oir;
	}

	@Override
	public void verifyLimitations(Long userId, Integer goodsId, Integer specificationId, Integer number) {
		GoodsLimit goodsLimit = new GoodsLimit();
		goodsLimit.setGoodsId(goodsId);
//		goodsLimit.setSpecificationId(specificationId);
		List<GoodsLimit> limitList = goodsMapper.getGoodsLimitList(goodsLimit);
		if (!CollectionUtils.isEmpty(limitList)) {
			for(GoodsLimit gl : limitList){
				if(gl.getLimitType() == null || gl.getLimitCount() == null || gl.getLimitCount() == 0){
					continue;
				}
				//1月限购XX件
				if(gl.getLimitType() == 1) {
					if(null != userId && userId > 0){
						//校验当月已经购买数据
						Integer buyCount = orderMapper.fetchGoodsBuyCount(userId,goodsId);
						buyCount = buyCount == null ? 0 : buyCount;
						if((number + buyCount) > gl.getLimitCount().intValue()){
							ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "此商品当月限购"+gl.getLimitCount()+"件");
						}
						//校验是否有未支付订单
						Integer unpayCount = orderMapper.fetchUnpayGoodsBuyCount(userId,goodsId);
						unpayCount = unpayCount == null ? 0 : unpayCount;
						if((number + unpayCount + buyCount) > gl.getLimitCount().intValue()){
							int shoppingNum = gl.getLimitCount().intValue() - unpayCount - buyCount;
							ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "此商品限购,您未支付的订单中有"+unpayCount+"件,本次可购买"+shoppingNum+"件");
						}
					}
				}
			}
		}

	}
	@Override
	public List<OrderInfoRes> userOrderList(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
//		if(orderInfoReq.getStart() == null || orderInfoReq.getStart() < 0){
//			orderInfoReq.setStart(0);
//		}
//		if(orderInfoReq.getLimit() == null || orderInfoReq.getLimit() < 0){
//			orderInfoReq.setLimit(10);
//		}

		List<OrderInfoRes> list =  orderMapper.userOrderLisr(orderInfoReq);

		if(CollectionUtils.isNotEmpty(list)){

			for(int i = list.size() - 1;i >= 0 ; i--){

				OrderInfoRes oir = list.get(i);
				/**
				if(oir.getExpirationTime().before(DateTime.now().toDate()) && oir.getPayStatus() == 0) {
					list.remove(i);
					continue;
				}
				**/
				List<OrderDetailsRes> orderDetailsRes = orderMapper.getOrderDetailListByOrderId(oir.getId());
				for(OrderDetailsRes odr : orderDetailsRes){
					odr.setTotalPrice(odr.getSalePrice() - odr.getCouponAmount());
					if(null !=odr && odr.getIsService() != null &&  odr.getIsService() == 1){
						odr.setThumbnailImage(oir.getOrderImg());
					}
				}
				oir.setOrderDetails(orderDetailsRes);
			}
		}
		return list;
	}

	@Override
	public Integer userOrderListCount(OrderInfoReq orderInfoReq) {
		return  orderMapper.userOrderLisrCount(orderInfoReq);
	}

	@Override
	public OrderInfoRes orderDetail(OrderInfoReq orderInfoReq) {
//		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() ==0){
//			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "用户ID不能为空");
//		}
		if(orderInfoReq.getId() == null || orderInfoReq.getId() ==0){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfoRes order = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == order){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单不存在");
		}
//		if(orderInfoReq.getUserId().intValue() != order.getUserId().intValue()){
//			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单不属于您,不能查看");
//		}
		getOrderDetailInfo(order,orderInfoReq.getId());
		return order;
	}

	private void getOrderDetailInfo(OrderInfoRes order, Integer orderInfoId) {
		// 获取详查详情
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoId);
		for (OrderDetailsRes odr : orderDetails) {
			GoodsRes goods = goodsMapper.getGoodsDetailById(odr.getGoodsId());
			odr.setMarketPrice(goods.getMarketPrice());
			odr.setSubject(goods.getSubject());
		}
		order.setOrderDetails(orderDetails);
	}

	@Override
	public OrderInfo getOrderInfoById(Integer orderId) {
		if(null == orderId || orderId == 0){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		return orderMapper.getOrderById(orderId);
	}

	@Override
	public OrderInfo checkOrderCouldPay(Integer orderId) {
		if(null == orderId || orderId == 0){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		//OrderInfoRes orderInfo = orderFetchMapper.getOrderInfoResById(orderId);
		OrderInfo orderInfo = orderMapper.getOrderInfoByOrderId(orderId);
		if(null == orderInfo){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单不存在");
		}
		//订单已支付
		if(orderInfo.getPayStatus().intValue() == OrderConstant.PAY_STATUS_PREPAID.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单已经支付过啦");
		}
		//无效订单
		if(orderInfo.getOrderStatus().intValue() == OrderConstant.ORDER_STATUS_INVALID.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "无效订单不可支付");
		}
		//过期订单
		if(orderInfo.getOrderStatus().intValue() == OrderConstant.ORDER_STATUS_EXPIRED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单已过期,请重新下单");
		}
		//订单已取消
		if(orderInfo.getOrderStatus().intValue() == OrderConstant.ORDER_STATUS_CANCELED.getOrderStatus()){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单已取消,请重新下单");
		}
		return orderInfo;
	}

	public OrderInfoRes getOrderInfoByOrderNo(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getOrderNo() == null || orderInfoReq.getOrderNo().isEmpty()){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单号不能为空");
		}
		OrderInfoRes orderInfoRes = orderMapper.getOrderByOrderNo(orderInfoReq.getOrderNo());
		if(null == orderInfoRes){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到订单号为"+orderInfoReq.getOrderNo()+"的订单");
		}
		if(orderInfoReq.getUserId().intValue() != orderInfoRes.getUserId().intValue()){
			ThrowUtils.throwException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该订单不属于您,不能查看");
		}
		getOrderDetailInfo(orderInfoRes,orderInfoRes.getId());
		return orderInfoRes;
	}

	@Override
	@Transactional
	public OrderInfoRes getOrderInfoByOrderNo(String orderNo) {

		return orderMapper.getOrderByOrderNo(orderNo);
	}

	@Override
	public List<OrderDetailsRes> getOrderDetailsList(Integer orderId) {
		return orderMapper.getOrderDetailList(orderId);
	}

	@Override
	public OrderInfoRes statisticsOrderCount(Integer userId) {
		if(null == userId){
			ThrowUtils.throwException(ErrorConstant.PARAM_ERROR.getErrorCode(), "用户ID不能为空");
		}
		return orderMapper.statisticsOrderCount(userId);
	}

	@Override
	public List<OrderInfo> getOrderListForOrderNoList(List<String> orderNoList) {
		if(CollectionUtils.isEmpty(orderNoList)){
			return new ArrayList<>();
		}
		return orderMapper.getOrderListForOrderNoList(orderNoList);
	}

	@Override
	public OrderInfoRes getOrderByThirdpartyOrderNo(String thirdpartyOrderNo) {
		return orderMapper.getOrderByThirdpartyOrderNo(thirdpartyOrderNo);
	}

}
